<?php
use oxide\data\Connection;
use module\content\model\Content;
use module\content\model\ContentUserExtension;
use oxide\util\Debug;

require_once (EDUPLUGIN_DIR . '/EduPlugin.php');
/**
 * Controller with Content related functions for Edu Plugin 
 */
class EduContentController 
{
	private
		$_context = null;
	
	public function __construct(oxide\http\Context $context) 
	{
		$this->_context = $context;
	}

	/**
	 * rendering section for the course, attributes, and lectures
	 * all based on loggin credential context
	 * @param Content $content
	 * @return void
	 */
	public function subContentAction(Content $content)
	{
		$auth = $this->_context->getAuth();
		$section = null;
		
		// if content is a section, the content will be set as section
		// if false, check content is not a course (no parent pk), 
		// hence the content should be lecture, note, file, etc belonging to the child of a section
		// if not (ie. blog, etc), then section is set as null
		if($content->content_type == 'section') {
			$section = $content;
		} else {
			if(!empty($content->parent_pk)) {
				$section = Content::find($content->parent_pk);
				if($section->content_type != 'section') {
					$section = null;
				}
			}
		}
		
		// find all contents with parent pk and status, ie. finding all section subcontents, where parent pk is the section
		// check if contents exist (for those without parent pk will refer to course content where parent pk is null)
		$contents = Content::selectByParent_PkAndStatus($content->content_pk, EduPlugin::STATUS_ACTIVE)->fetchAll();
		
		// if it is course,
		// render the subcontents (i.e. sections)
		if($content->content_type == 'course') {
			$this->_renderSubContents($contents);
		}
		
		// if it is section,
		// check if user has registered for course(section)
		// and display the subcontent of the section if only user has registered and paid for the course
		else if ($content->content_type == 'section') {
			$content_user_extension = null;
			
			if ($auth->hasIdentity()) {
				$user = $auth->getIdentity();

				// check if user has been registered for the course		
				$content_user_extension = ContentUserExtension::findByContent_pkAndUser_pk(
						$content->content_pk, 
						$user->user_pk);
				
				// set this to the content as edu_content_user_extension for the section
				// so that menu can read to ensure that the user is subscribed and paid for the course
				$content['edu_content_user_extension'] = $content_user_extension;
				
				// if user has been registered and paid for the course (1),
				// display the subcontents of the course-section, ie. lectures, notes, files, etc
				if ($content_user_extension->edu_status == EduPlugin::STATUS_ACTIVE) {
					$this->_renderSubContents($contents);
				
				} else {
					// if user is not logged in, he will see section and registration info
					// render the attributes (e.g. cost, instructor, location, etc)
					$this->_renderAttributeForContent($content);	
					
				}
				
			} else {
				// if user is not logged in, he will see section and registration info
				// render the attributes (e.g. cost, instructor, location, etc)
				$this->_renderAttributeForContent($content);

			}
			// display the Login to register/Register now
			$this->_renderRegisterOrLoginForContent($content_user_extension);
			
		}
		
		// display layout menu, it will only be shown if user is logged in
		if ($auth->hasIdentity()) {
			// get the edu content user extension, and check if the user has registered and paid for the lesson
			$edu_cue = $content['edu_content_user_extension'];
			if ($edu_cue['edu_status'] == EduPlugin::STATUS_ACTIVE) { 
				$this->_renderLayoutMenu($section);
			}
		}
	}
	
	/**
	 * display for the menu
	 * @param type $section
	 * @return type 
	 */
	private function _renderLayoutMenu($section)
	{		
		if(!$section) return;
		
		$menus = array(); // holds menu array for the layout
		
		// add the section to the layout menu
		$menus[$section->title] = "/content/view/{$section->permalink}";	
		
		
		// retrieve sub tags for content pk, with the sub content pks
		$tags = $this->_retrieveSubTagsForPk($section->content_pk);
		foreach ($tags as $tag) {
			$section_tags[$tag['title']] =  "/content/list/tag/{$tag['term']}";
		}

		$content_types = $this->_retrieveSubContentTypeForPk($section->content_pk);
		foreach ($content_types as $content_type) {
			$section_content_types[$content_type['title']] = "/content/list/type/{$content_type['term']}";
		}

		// Set the Tags/Content Types to the menus
		$menus['Tags'] = !empty($section_tags) ? $section_tags : array();
		$menus['Content Types'] = !empty($section_content_types) ? $section_content_types : array();
		
		
		$viewController = $this->_context->getViewController();
		$script = EDUPLUGIN_DIR . '/layout-menu.phtml';
		$view  = new \oxide\application\View($script);
		$view->assign('menus', $menus);
		$view->setIdentifier('EDU_SIDE_NAV');
		$viewController->getView()->addView($view);
		//oxide\application\View::share('EDU_SIDE_NAV', $view);
	}
	
	/**
	 * validation and authenication checks before view content is rendered
	 * @param mixed $content
	 * @param mixed $auth
	 * @return type
	 * @throws Exception 
	 */
	public function contentViewValidation($content, $auth)
	{	
		\oxide\application\View::load('_messenger');
		
		// managed supported types
		if ($this->_validateContentType($content->content_type)) {
		
			// if the content is a supported type, and it's not course or section, then it is a sub content
			// if it it's course or section then do nothing
			if ($content->content_type == 'course' || $content->content_type == 'section') { return; }
			
			// users without authentication will be redirected to login
			if (!$auth->hasIdentity()) {
				_messenger::set('Login required to access requested page.', '/user/login', _messenger::ERROR);
				$this->_context->getResponse()->setRedirect('/user/login');
				$this->_context->getResponse()->sendHeaders();
			}

			// check user's status for the course, 
			// since it's a sub content, then use the parent pk to check against the cue.content_pk of user
			// if user has does not have active status for the course, the user has no access to the sub content
			$identity = $auth->getIdentity();
			$cue = module\content\model\ContentUserExtension::findByContent_pkAndUser_pk($content->parent_pk, $identity->user_pk);
			
			// authenticated users who are trying to access sub contents that they do not paid for
			if (empty($cue) || $cue->edu_status != EduPlugin::STATUS_ACTIVE) {
//				throw new Exception('Error: You do not have access to this course contents', 901);
				_messenger::set('Login required to access requested page.', '/user/login', _messenger::ERROR);
				$this->_context->getResponse()->setRedirect('/user/login');
				$this->_context->getResponse()->sendHeaders();
			}
			
		}
	}
	
	/**
	 * retrieve all sub content types (e.g. lectures, notes, etc) based on content pk
	 * @param int $content_pk
	 * @return array
	 */
	private function _retrieveSubContentTypeForPk($content_pk)
	{
		$query = new \oxide\data\sql\SelectQuery('term', Connection::sharedInstance());
		$query->distinct();
		$query->columns(array('term.term_pk', 'term.term', 'term.title', 'content.permalink'));
		$query->join('content', array('content.type_pk' => 'term.term_pk'), \oxide\data\Connection::JOIN_LEFT);
		$query->where('content.parent_pk', $content_pk, \oxide\data\Connection::OP_EQ);

		$stmt = $query->execute();
		return $stmt;
	}
	
	/**
	 * retrieve all sub content tags (e.g. lectures, notes, etc) based on content pk
	 * @param array $content_pk
	 * @return array 
	 */
	private function _retrieveSubTagsForPk($content_pk)
	{
      $query = new \oxide\data\sql\SelectQuery('content_tag', Connection::sharedInstance());
		$query->select(array('term', 'title', 'term_pk'), 'term');
		$query->distinct();
		$query->join('term', array('term.term_pk' => 'content_tag.term_pk'), \oxide\data\Connection::JOIN_INNER);
		$query->join('content', array('content.content_pk' => 'content_tag.content_pk'), oxide\data\Connection::JOIN_INNER);
		$query->where('content.parent_pk', $content_pk);
		$query->order('term');
		
      $stmt= $query->execute();		
		return $stmt;
	}
	
	/**
	 * render the sub contents such as title and permalink of subcontent
	 * @param mixed $contents 
	 */
	private function _renderSubContents($contents)
	{
		if(empty($contents)) return;
		// loop through contents to display the 
		foreach($contents as $content) {
			_html::start('h4');
			_html::a('/content/view/' . $content['permalink'], $content['title']);
			_html::end();		
		}
	}
	

	/**
	 * display the attributes (e.g. cost, location, etc) for the content
	 * @param mixed $content 
	 */
	private function _renderAttributeForContent($content)
	{
		// retrieve the list of keys from metadata
		$metadata = $content->metadata();
		$keys = array(
					 'EduPlugin_cost', 
					 'EduPlugin_instructor', 
					 'EduPlugin_location', 
					 'EduPlugin_days', 
					 'EduPlugin_time',
					 'EduPlugin_start', 
					 'EduPlugin_end'
				);
		foreach ($keys as $key) {
			// remove the prefix and uppercase for the first letter
			// and display in dd/dt
			$uckey = ucfirst(str_replace('EduPlugin_', '', $key)).':';
			_html::tag('dt', $uckey, array('title' => $key));
			_html::tag('dd', $metadata->$key. ' | ');
		}
		_html::tag('br', '');
	}
	
	/**
	 * display login to register/register now/registered but not paid
	 * @param int $content_pk 
	 */
	private function _renderRegisterOrLoginForContent($content_user_extension)
	{
		// check if content user extension is empty
		// i.e. (the user is not logged in, unable to retrieve the content user extension, hence the default is empty)
		//		then display login to register
		// if not, the content user extension has course data
		//		check if the status for the content user extension is NULL or unpaid (0)
		//		and display based on the requirement
		
		if (empty($content_user_extension)) {
			_html::a('/user/login', 'Login to register');
			return;
		}
		
		if (is_null($content_user_extension->edu_status)) {
			_html::a("/content/course/register/{$content_user_extension->content_pk}", 'Register now');
		} else if ($content_user_extension->edu_status != EduPlugin::STATUS_ACTIVE) {
			$status_text = EduPlugin::getStringForSectionStatus($content_user_extension->edu_status);
			_html::tag('span', 'Course '.$status_text);
		}
	}
	
	/**
	 * check to ensure that the content type is supported
	 * @param string $content_type
	 * @return boolean 
	 */
	private function _validateContentType($content_type) 
	{	
		// check if type is a valid term, and get the name of the term
		$term = module\content\model\Term::findByTerm($content_type);

		// check if the term is a valid supported type
		// if not valid against defined support types, return as false
		// else return as true
		
		if (empty($term)) { return false; }
		if (!in_array($term->term, EduPlugin::getSupportedTypes())) { return false; }
		
		return true;
	}
}